import { PageContainer } from '@ant-design/pro-layout';
import { useEffect, useRef, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProForm, { ModalForm, ProFormText, ProFormRadio, ProFormDigit, ProFormDatePicker, ProFormSelect, QueryFilter, ProFormDateRangePicker } from '@ant-design/pro-form';
import { AutoComplete, Button, Col, Form, message, Modal, Row, Statistic, Table } from 'antd';
import { DownOutlined, PlusOutlined } from '@ant-design/icons/lib/icons';
import { createOrder, deleteOrder, queryOrders, updateOrder, queryContries, queryUsers } from '@/services/ant-design-pro/api';
import { useAccess, Access } from 'umi';
import { contrySelectRequest, userSelectRequest } from './common';
import moment from 'moment';
import ExportJsonExcel from 'js-export-excel';


const payTypes = [
    { label: "USDT", value: "usdt" },
    { label: "微信", value: "wechat" },
    { label: "支付宝", value: "alipay" },
];

const payTypeMap = {
    "usdt": "USDT",
    "wechat": "微信",
    "alipay": "支付宝",
    "": ""
}

const convertDateToTime = (value) => {
    if (value) {
        let t = Date.parse(value);
        return new Date(t);
    }
    return null
}

const formatTimeToDateString = (value) => {
    if (value) {
        return moment(value).format("YYYY-MM-DD");
    }
    return ""
}
const convertFormValue = (values) => {
    values.order_create_time = convertDateToTime(values.order_create_time)
    values.pay_time = convertDateToTime(values.pay_time)
    values.return_time = convertDateToTime(values.return_time)
    values.refund_time = convertDateToTime(values.refund_time)
    values.final_time = convertDateToTime(values.final_time)
}
const getPayText = (values, field) => {
    let type = payTypeMap[values[field + "_type"]] || "-"
    let value = values[field + "_value"] || "-"
    let time = values[field + "_time"] || ""
    let dateStr = "";
    if (time) {
        let date = Date.parse(time);
        dateStr = moment(date).format("YYYY-MM-DD")
    }
    return `${value}(${type}) ${dateStr}`
}


export default () => {
    const actionRef = useRef<ActionType>();
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<any>();
    const [tableData, setTableData] = useState<any>([]);
    const [paySum, setPaySum] = useState<any>({});
    const [customerAutoFillList, setCustomerAutoFillList] = useState<any>([]);
    const access = useAccess();
    const tableRequest = async (
        params: {
            current?: number;
            pageSize?: number;
        },
    ) => {
        let userResp: any = await queryOrders(params);
        setTableData(userResp.data)
        return {
            data: userResp.data,
            success: true,
        }
    }
    const downloadExcel = () => {
        const data = tableData;
        var option = {};
        let dataTable = [];
        if (data) {
            for (let i in data) {
                if (data) {
                    let obj = {
                        'ID': data[i].id,
                        '国家': data[i].country,
                        '客户': data[i].customer_name,
                        '销售员': data[i].nickname,
                        '实际结算量': data[i].count,
                        '客户下单量': data[i].customer_count,
                        '实际完成量': data[i].complete_count,
                        '单价': data[i].price,
                        '成本': data[i].cost_price,
                        '利润': (data[i].price - data[i].cost_price) * data[i].count,
                        '实际结算成本': data[i].count * data[i].cost_price,
                        '应收款': data[i].count * data[i].price,
                        'USDT汇率': data[i].usdt_exchange_rate,
                        '收款类型': payTypeMap[data[i].pay_type],
                        '收款额': data[i].pay_value,
                        '收款时间': formatTimeToDateString(data[i].pay_time),
                        '返点类型': payTypeMap[data[i].return_type],
                        '返点额': data[i].return_value,
                        '返点时间': formatTimeToDateString(data[i].return_time),
                        '退款类型': payTypeMap[data[i].refund_type],
                        '退款额': data[i].refund_value,
                        '退款时间': formatTimeToDateString(data[i].refund_time),
                        '尾款类型': payTypeMap[data[i].final_type],
                        '尾款额': data[i].final_value,
                        '尾款时间': formatTimeToDateString(data[i].final_time),
                        '订单时间': formatTimeToDateString(data[i].order_create_time),
                        '备注': data[i].comment,

                    }
                    dataTable.push(obj);
                }
            }
        }
        option.fileName = '订单信息'
        option.datas = [
            {
                sheetData: dataTable,
                sheetName: 'sheet',
                sheetFilter: ['ID', '国家', '客户', '销售员', '客户下单量', '实际完成量', '实际结算量', '单价', '成本', '利润', '实际结算成本', '应收款', 'USDT汇率', '收款类型', '收款额', '收款时间', '返点类型', '返点额', '返点时间', '退款类型', '退款额', '退款时间', '尾款类型', '尾款额', '尾款时间', '订单时间', '备注'],
                sheetHeader: ['ID', '国家', '客户', '销售员', '客户下单量', '实际完成量', '实际结算量', '单价', '成本', '利润', '实际结算成本', '应收款', 'USDT汇率', '收款类型', '收款额', '收款时间', '返点类型', '返点额', '返点时间', '退款类型', '退款额', '退款时间', '尾款类型', '尾款额', '尾款时间', '订单时间', '备注'],
            }
        ];

        var toExcel = new ExportJsonExcel(option);
        toExcel.saveExcel();
    }

    useEffect(() => {
        console.log("order access", access)
        tableRequest({})
    }, [])

    useEffect(() => {
        let customerMap = new Map();
        let customerOptions: { value: any; }[] = [];
        let totalPrice = 0;
        let usdtPay = 0;
        let otherPay = 0;
        let profit = 0;
        tableData.forEach((val) => {
            totalPrice += val.price * val.count;
            if (val.pay_type == "usdt") {
                usdtPay += val.pay_value;
            } else {
                otherPay += val.pay_value;
            }
            if (val.final_type == "usdt") {
                usdtPay += val.final_value;
            } else {
                otherPay += val.final_value;
            }
            profit += (val.price - val.cost_price) * val.count;
            customerMap.set(val.customer_name, 1)
        })

        customerMap.forEach((value, key) => {
            customerOptions.push({ value: key });
        });
        setCustomerAutoFillList(customerOptions)
        setPaySum({
            totalPrice,
            usdtPay,
            otherPay,
            profit
        })
    }, [tableData])
    const columns: ProColumns<AnalyserNode>[] = [
        { title: 'ID', dataIndex: 'id' },
        { title: '国家', dataIndex: 'country', search: true, request: contrySelectRequest },
        { title: '客户', dataIndex: 'customer_name', },
        { title: '客户下单量', dataIndex: 'customer_count' },
        { title: '实际完成量', dataIndex: 'complete_count' },
        { title: '实际结算量', dataIndex: 'count', },
        { title: '单价', dataIndex: 'price', },
        { title: '成本', dataIndex: 'cost_price', },
        { title: '实际结算成本', render: (val, record) => record.count * record.cost_price },
        { title: '利润', render: (val, record) => (record.price - record.cost_price) * record.count },
        { title: '应收款', dataIndex: 'total_price', render: (val, record) => record.count * record.price },
        { title: 'U汇率', dataIndex: 'usdt_exchange_rate', },
        { title: '收款信息', render: (val, record) => getPayText(record, "pay") },
        { title: '返点信息', render: (val, record) => getPayText(record, "return") },
        { title: '退款信息', render: (val, record) => getPayText(record, "refund") },
        { title: '尾款信息', render: (val, record) => getPayText(record, "final") },
        { title: '备注', dataIndex: 'comment' },
        {

            title: '销售员', dataIndex: 'username',
            render: (text, record, idx) => {
                return record.username + "(" + record.nickname + ")"
            },
            search: access.isAdmin,
            request: userSelectRequest
        },
        { title: '派单员', dataIndex: 'dispatch_nickname' },
        { title: '派单备注', dataIndex: 'dispatch_comment' },
        {
            title: '订单日期',
            dataIndex: 'order_create_time',
            valueType: 'dateRange',
            search: true,
            render: (text, record) => {
                return formatTimeToDateString(record.order_create_time)
            }
        },
        {
            title: '操作',
            valueType: 'option',
            render: (text, record, _, action) => [
                <a
                    key="editable"
                    onClick={() => {
                        handleUpdateModalVisible(true);
                        setCurrentRow(record);
                    }}
                >
                    编辑
                </a>,
                (access.isAdmin &&
                    <a
                        key="delete"
                        onClick={(item) => {
                            Modal.confirm({
                                title: <h3>提示</h3>,
                                content: "确认删订单 " + record.id + "?",
                                onOk: async () => {
                                    let result = await deleteOrder(record)
                                    if (result.code == 0) {
                                        message.success("删除成功");
                                        actionRef.current?.reload();
                                    }
                                }
                            })

                        }}
                    >
                        删除
                    </a>
                )
            ],
        },
    ];
    columns.forEach(column => {
        if (typeof (column.search) == "undefined") {
            column.search = false;
        }
    })
    return <PageContainer>
        <Row gutter={16}>
            <Col span={12}>
                <Statistic title="应收总额" value={paySum.totalPrice} />
            </Col>
            <Col span={12}>
                <Statistic title="USDT付款" value={paySum.usdtPay} />
            </Col>
            <Col span={12}>
                <Statistic title="其他付款" value={paySum.otherPay} />
            </Col>
            <Col span={12}>
                <Statistic title="利润" value={paySum.profit} />
            </Col>

        </Row>,

        <ProTable<any>
            actionRef={actionRef}
            rowKey="id"
            columns={columns}
            request={tableRequest}
            search={true}
            toolBarRender={() => [
                <Button key="out" onClick={downloadExcel}>
                    导出数据
                    <DownOutlined />
                </Button>,
                (access.isAdmin &&
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        <PlusOutlined />新建
                    </Button>
                ),
            ]}
        />

        <Modal
            title="编辑数据"
            visible={updateModalVisible}
            onCancel={() => {
                handleUpdateModalVisible(false)
            }}
            onOk={() => { }}
            okText="确认"
            cancelText="取消"
            destroyOnClose={true}
            footer={null}
        >
            <ProForm onFinish={async (values: any) => {
                convertFormValue(values)
                let result = await updateOrder(values)
                if (result.code == 0) {
                    handleUpdateModalVisible(false)
                    actionRef.current?.reload();
                    message.success("更新成功")
                }
            }} >
                <ProFormText name="id" width="md" label="ID" initialValue={currentRow?.id} disabled
                    rules={[{ required: true }]}
                />
                <ProFormDatePicker name="order_create_time" width="md" label="日期" disabled
                    rules={[{ required: true }]}
                    initialValue={currentRow?.order_create_time}
                />
                <ProFormText name="customer_name" label="客户名称" width="md" rules={[{ required: true }]} initialValue={currentRow?.customer_name} />
                <ProFormText name="comment" label="备注" width="md" initialValue={currentRow?.comment} />
                <ProFormSelect name="country" width="md" label="国家" disabled
                    rules={[{ required: true }]}
                    initialValue={currentRow?.country}
                    request={contrySelectRequest}
                />
                <ProFormDigit name="price" label="单价" width="md" min={0} rules={[{ required: true }]} initialValue={currentRow?.price} disabled />
                <ProFormDigit name="count" label="实际结算量" width="md" min={0} rules={[{ required: true }]} initialValue={currentRow?.count} />
                <ProFormDigit name="usdt_exchange_rate" label="USDT汇率" width="md" initialValue={currentRow?.usdt_exchange_rate} />
                <ProFormSelect name="pay_type" width="md" label="收款类型" initialValue={currentRow?.pay_type}
                    rules={[{ required: true }]}
                    options={payTypes}
                />
                <ProFormDigit name="pay_value" label="收款金额" width="md" min={0} rules={[{ required: true }]} initialValue={currentRow?.pay_value} />
                <ProFormDatePicker name="pay_time" width="md" label="收款日期"
                    rules={[{ required: true }]}
                    initialValue={currentRow?.pay_time}
                />
                <ProFormSelect name="return_type" width="md" label="返点类型" initialValue={currentRow?.return_type}
                    options={payTypes}
                />
                <ProFormDigit name="return_value" label="返点金额" width="md" min={0} initialValue={currentRow?.return_value} />
                <ProFormDatePicker name="return_time" width="md" label="返点日期"
                    initialValue={currentRow?.return_time}
                />
                <ProFormSelect name="refund_type" width="md" label="退款类型" initialValue={currentRow?.refund_type}
                    options={payTypes}
                />
                <ProFormDigit name="refund_value" label="退款金额" width="md" min={0} initialValue={currentRow?.refund_value} />
                <ProFormDatePicker name="refund_time" width="md" label="退款日期"
                    initialValue={currentRow?.refund_time}
                />
                <ProFormSelect name="final_type" width="md" label="尾款类型" initialValue={currentRow?.final_type}
                    options={payTypes}
                />
                <ProFormDigit name="final_value" label="尾款金额" width="md" min={0} initialValue={currentRow?.final_value} />
                <ProFormDatePicker name="final_time" width="md" label="尾款日期"
                    initialValue={currentRow?.final_time}
                />

            </ProForm>
        </Modal>

        <ModalForm
            title={"新建订单"}
            // width="400px"
            visible={createModalVisible}
            onVisibleChange={handleModalVisible}
            onFinish={async (values) => {
                convertFormValue(values)
                let result = await createOrder(values)
                if (result.code == 0) {
                    handleModalVisible(false);
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                }
            }}
        >
            <ProForm.Group>
                <Form.Item label="客户名称" name="customer_name" style={{ width: 328 }} rules={[{ required: true }]} initialValue={currentRow?.customer_name}
                >
                    <AutoComplete options={customerAutoFillList} />
                </Form.Item>
                <ProFormDatePicker name="order_create_time" width="md" label="日期"
                    rules={[{ required: true }]}
                    initialValue={new Date()}
                />
            </ProForm.Group>
            <ProFormText name="comment" label="备注" width="md" />
            <ProForm.Group>
                <ProFormSelect name="country" width="md" label="国家"
                    rules={[{ required: true }]}
                    request={contrySelectRequest}
                />
                <ProFormDigit name="price" label="单价" width="md" min={0}
                    rules={[
                        { required: true },
                    ]}
                />
            </ProForm.Group>
            <ProFormDigit name="count" label="实际结算量" width="md" min={0} rules={[{ required: true }]} />
            <ProFormDigit name="usdt_exchange_rate" label="USDT汇率" width="md" />
            <ProForm.Group label="收款信息">
                <ProFormSelect name="pay_type" width="md" label="收款类型"
                    rules={[{ required: true }]}
                    options={payTypes}
                />
                <ProFormDigit name="pay_value" label="收款金额" width="md" min={0} rules={[{ required: true }]} />
                <ProFormDatePicker name="pay_time" width="md" label="收款日期"
                    rules={[{ required: true }]}
                />
            </ProForm.Group>
            <ProForm.Group label="返点信息">
                <ProFormSelect name="return_type" width="md" label="返点类型"
                    options={payTypes}
                />
                <ProFormDigit name="return_value" label="返点金额" width="md" min={0} />
                <ProFormDatePicker name="return_time" width="md" label="返点日期" />
            </ProForm.Group>
            <ProForm.Group label="退款信息">
                <ProFormSelect name="refund_type" width="md" label="退款类型"
                    options={payTypes}
                />
                <ProFormDigit name="refund_value" label="退款金额" width="md" min={0} />
                <ProFormDatePicker name="refund_time" width="md" label="退款日期" />
            </ProForm.Group>
            <ProForm.Group label="尾款信息">
                <ProFormSelect name="final_type" width="md" label="尾款类型" options={payTypes} />
                <ProFormDigit name="final_value" label="尾款金额" width="md" min={0} />
                <ProFormDatePicker name="final_time" width="md" label="尾款日期" />
            </ProForm.Group>


        </ModalForm>
    </PageContainer>
};
